//
//  DDTCPListenThread.m
//  PrivateCloud
//
//  Created by mars on 13-10-19.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "DDTCPListenThread.h"
#import "GCDAsyncSocket.h"
#import "DDExchangeTokenMask.h"
#import "DDHdrCloud.h"
#import "DDExchangeTokenMaskACK.h"
#import "NSString+md5.h"
#import "DDLogin.h"
#import "DDLoginACK.h"
#import "DDClientInfo.h"
#import "DDExchangeInformation.h"
#import "DDTCPListenThread.h"
#import "DDCommentDic.h"
#import "DDConstants.h"
#import "DDReportFile.h"
#import "DDReportFileACK.h"
#import "DDVerifyThread.h"
#import "DDDownloadFileACK.h"
#import "IOOperation.h"
#import "DDRefreshFile.h"
#import "DDRefreshFileACK.h"
#import "DDUploadFileACK.h"
#import "DDDownloadFile.h"
#import "DDUploadAddressBook.h"
#import "DDUploadAddressBookACK.h"
#import "DDDownLoadAddress.h"
#import "DDDownLoadAddressACK.h"
#import "DDAddressBookUtils.h"
#import "DDDeleteFile.h"
#import "FileOperation.h"
#import "DDDeleteFileACK.h"
#import "TestAddressBook.h"
#import "AppUtil.h"
#include "DDAppDelegate.h"
#include <AssetsLibrary/AssetsLibrary.h>
#include <AVFoundation/AVFoundation.h>

#define RECV_HEAD_TAG 1
#define RECV_BODY_TAG 2

static DDTCPListenThread *_sharedTCPListener;

@implementation DDTCPListenThread

@synthesize recvSocket = _recvSocket;
@synthesize connectCompleteCallback;
@synthesize dealFileCallback,totalLength,currentPer,alreadyDownloadLength,currentDownloadFileList,downloadBookCallback,refreshCallback,remeberFlag;

+ (DDTCPListenThread *)sharedTCPListener{
    if(_sharedTCPListener == nil){
        _sharedTCPListener = [[DDTCPListenThread alloc]init];
    }
    return  _sharedTCPListener;
}

- (id)init{
    NSLog(@"tcp log----------");
    self = [super init];
    //dispatch_queue_t queue = dispatch_queue_create("com.marschen.privatecloud.recv",DISPATCH_QUEUE_SERIAL);
    _recvSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSLog(@"RECV---打开%d端口，开始接收来自PC的连接",TCP_LISTEN_PORT);
    [_recvSocket acceptOnPort:TCP_LISTEN_PORT error:nil];
    
    sendThread = [DDVerifyThread sharedVerifyThread];
    return self;
}
#pragma mark Socket Delegate

- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket{
    NSLog(@"RECV---完成了与PC端的连接，准备读取第一个数据头");
    _recvSocket = newSocket;
    [_recvSocket setDelegate:self];
    [_recvSocket readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
    
}

- (void)socket:(GCDAsyncSocket* )sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"RECV---接收到了来自PC端的数据");
    NSTimeInterval time1=[[NSDate date] timeIntervalSince1970]*1000;
    double a1 = time1;      //NSTimeInterval返回的是double类型
    if(tag == RECV_HEAD_TAG){
        curHdr = [[DDHdrCloud alloc]initWithData:data];
        [curHdr printHead];
        int length = [curHdr length];
        int leftLength = length - HEADER_LENGTH;
        NSLog(@"RECV length-------%d",length);
        if(leftLength == 0){
            int curCmd = [curHdr cmd];
            if(curCmd == CloudCmd_ExchangeInformationAck){
                NSLog(@"RECV---CloudCmd_ExchangeInformationAck");
            }
            if(curCmd == CloudCmd_Heartbeat){
                NSLog(@"RECV---CloudCmd_Heartbeat");
            }
            if (curCmd == CloudCmd_ReportFileAck) {
                NSLog(@"RECV---CloudCmd_ReportFileAck");
            }
            if (curCmd == CloudCmd_RefreshFile) {
                NSLog(@"RECV---CloudCmd_RefreshFile");
                //收到刷新文件命令，直接调用上传文件列表的程序
                NSArray* localFolderInfos = [DDConstants getLocalFolders];
                DDRefreshFileACK* refreshFileAck = [[DDRefreshFileACK alloc]init];
                [sendThread sendMessage:refreshFileAck];
                [sendThread reportFileList:localFolderInfos];
            }
            if(curCmd == CloudCmd_UploadFileAck){
                NSLog(@"RECV---CloudCmd_UploadFileAck");
            }
            if(curCmd == CloudCmd_UploadAddressBookAck){
                NSLog(@"RECV---CloudCmd_UploadAddressBookAck");
            }
            if (curCmd == CloudCmd_RefreshFileAck) {
                NSLog(@"RECV---CloudCmd_RefreshFileAck");
            }
            if (curCmd == CloudCmd_Logout) {
                NSLog(@"RECV---CloudCmd_Logout");
                //开始执行退出操作
                DDAppDelegate* appDelegate =(DDAppDelegate*)[[UIApplication sharedApplication]delegate];
                //                [[[UIApplication sharedApplication]delegate]closeAndDisplayLogin];
                [appDelegate closeAndClead];
                
            }
            //[curHdr release];
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else{
            [sock readDataToLength:leftLength withTimeout:-1 tag:RECV_BODY_TAG];
        }
        NSTimeInterval time2=[[NSDate date] timeIntervalSince1970]*1000;
        double a2 = time2;      //NSTimeInterval返回的是double类型
        
        
        NSLog(@"time-----------------%f",a2 - a1);
    }
    else if(tag == RECV_BODY_TAG){
        NSTimeInterval time3=[[NSDate date] timeIntervalSince1970]*1000;
        double a3 = time3;      //NSTimeInterval返回的是double类型
        NSMutableData* entity = [[NSMutableData alloc]init];
        [entity appendData:[curHdr entity]];
        [entity appendData:data];
        int curCmd = [curHdr cmd];
        if(curCmd == CloudCmd_ExchangeTokenMask){
            NSLog(@"RECV---CloudCmd_ExchangeTokenMask");
            //PC发给我们的Token
            DDExchangeTokenMask* exchangeTokenMask = [[DDExchangeTokenMask alloc]initWithData:entity];
            //我们发送给PC的Token
            DDExchangeTokenMaskACK* exchangeTokenMaskAck = [[DDExchangeTokenMaskACK alloc]initWithTokenMask:@"test"];
            [sock writeData:[exchangeTokenMaskAck entity] withTimeout:-1 tag:CloudCmd_ExchangeTokenMaskAck];
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else if(curCmd == CloudCmd_Login){
            NSLog(@"RECV---CloudCmd_Login");
            DDLogin* login = [[DDLogin alloc]initWithData:entity];
            //FIX ME应该判断一下是否登陆成功，这里直接返回登陆成功
            DDLoginACK* loginAck = [[DDLoginACK alloc]initWithResult:0];
            [sock writeData:[loginAck entity] withTimeout:-1 tag:CloudCmd_LoginAck];
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else if(curCmd == CloudCmd_ExchangeInformation){
            NSLog(@"RECV---CloudCmd_ExchangeInformation");
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
            DDExchangeInformation* exchangeInfo = [[DDExchangeInformation alloc]initWithData:entity];
            NSUserDefaults* userDefaults = [[NSUserDefaults alloc]init];
            NSString* serverId = [exchangeInfo getCloudId];
            NSString* serverName = [exchangeInfo getCloudName];
            NSString* serverType = [exchangeInfo getTypeName];
            
            [userDefaults setObject:serverId forKey:SERVER_CLOUD_ID_KEY];
            [userDefaults setObject:serverName forKey:SERVER_CLOUD_NAME_KEY];
            [userDefaults setObject:serverType forKey:SERVER_CLOUD_TYPE_KEY];
            [userDefaults release];
            
        }
        else if(curCmd == CloudCmd_ReportFile){
            NSLog(@"RECV---CloudCmd_ReportFile");
            DDConstants *constants = [DDConstants sharedConstants];
            DDReportFile *report = [[DDReportFile alloc]initWithData:entity];
            if([report getType] == 0){
                [DDConstants removeAllFilesByCode:SERVER_CODE];
            }
            NSArray* fileInfos = [report getFileInfos];
            if(fileInfos != nil && [fileInfos count] != 0){
                [DDConstants addServerFiles:fileInfos];
            }
            
            if([report getType] == 2){
                NSLog(@"RECV--------------接收上报文件完毕");
                DDReportFileACK* reportFileAck = [[DDReportFileACK alloc]init];
                [sock writeData:[reportFileAck entity] withTimeout:-1 tag:CloudCmd_ReportFileAck];
                
                //POINT 在该时间点认为连接服务器的操作已经完成
                if ([DDTCPListenThread sharedTCPListener].connectCompleteCallback != nil) {
                    [[DDTCPListenThread sharedTCPListener].connectCompleteCallback onConnectCompleteOn:nil andCode:LOGIN_SUCCESS];
                    
                    //登陆完成之后需要向服务器上报本地文件列表
                    NSArray* localFolderInfos = [DDConstants getLocalFolders];
                    [sendThread reportFileList:localFolderInfos];
                }
                
            }
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else if (curCmd == CloudCmd_DownloadFileAck){
            NSLog(@"RECV---CloudCmd_DownloadFileAck-----");
           
            IOOperation* ioOp = [[IOOperation alloc]init];
            
            DDDownloadFileACK* downFileAck = [[DDDownloadFileACK alloc]initWithData:entity];
            
            //type是0的情况就是正常的数据包
            if([downFileAck getType]== 0){
                NSData* writeData = [downFileAck getData];
                int writeId = [downFileAck getUid];
                long writeOffset = [downFileAck getOffset];
                [ioOp writeData:writeData andOffset:writeOffset andUID:writeId];
            }
            //type是-1的情况说明服务器取消了下载
            else if([downFileAck getType] == 0xFFFFFFFF){
                if (dealFileCallback != nil) {
                    [dealFileCallback onDealFileComplete:nil andCode:DOWNLOAD_CANCEL];
                }
            }
            //剩下的情况说明已经下载到了文件的末尾,并将文件信息存入本地文件文件数组当中
            else{
                NSLog(@"end-----------------");
                NSData* writeData = [downFileAck getData];
                int writeId = [downFileAck getUid];
                long writeOffset = [downFileAck getOffset];
                //[ioOp writeData:writeData andOffset:writeOffset andUID:writeId];
                
                DDFileInfo* downloadFileInfo = [DDConstants getServerFileInfoById:[downFileAck getUid]];
                long fileLength = [ioOp getFileLength:[downloadFileInfo fileName]];
                [downloadFileInfo setFileLength:fileLength];
                //[DDConstants addFile:downloadFileInfo andCode:LOCAL_CODE];
                if (dealFileCallback != nil) {
                    [dealFileCallback onDealFileComplete:nil andCode:DOWNLOAD_SUCCESS];
                }
                
                
                NSString * type = [DDConstants getFileInfoType:[downloadFileInfo fileName]];
                //判断当前的文件是否是图片，如果是图片，是图片，就保存在相册当中
                if ([type isEqualToString:(@"photo")]) {
                    NSString* filePath = [NSString stringWithFormat:@"%@%@/%@",[AppUtil getDocPath],type,[downloadFileInfo fileName]];
                    //将文件保存在设备的相册当中
                    [self save:filePath];
                }
                else if([type isEqualToString:(@"video")]){
                    NSString* filePath = [NSString stringWithFormat:@"%@%@/%@",[AppUtil getDocPath],type,[downloadFileInfo fileName]];
                    
                    NSLog(@"app----------->%@",filePath);
                    [self saveV:filePath];
                }
                else{
                    DDFileInfo* downloadFileInfo = [DDConstants getServerFileInfoById:[downFileAck getUid]];
                    long fileLength = [ioOp getFileLength:[downloadFileInfo fileName]];
                    [downloadFileInfo setFileLength:fileLength];
                    [DDConstants addFile:downloadFileInfo andCode:LOCAL_CODE];
                }
            }
            alreadyDownloadLength += [downFileAck getLength];
            int thisPercent = (int) ((((float) alreadyDownloadLength) / totalLength) * 100);
            if(thisPercent > currentPer){
                currentPer = thisPercent;
                if(dealFileCallback != nil){
                    //当代理对象不为空时，调用该方法
                    [dealFileCallback onProgressChanged:currentPer];
                }
                NSLog(@"curper---------%d",currentPer);
                if (currentPer == 100) {
                    if (dealFileCallback != nil) {
                        [dealFileCallback onDealFileComplete:nil andCode:DOWNLOAD_SUCCESS];
                    }
                    alreadyDownloadLength = 0;
                    totalLength = 0;
                    currentPer = 0;
                }
            }
            [downFileAck release];
            //[curHdr release];
            [ioOp release];
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else if(curCmd == CloudCmd_DownloadFile){
            NSLog(@"RECV---收到CloudCmd_DownloadFile指令");
            //接收到请求下载文件的消息，需要发送DownnloadFileAck指令响应
            DDDownloadFile* downloadFile = [[DDDownloadFile alloc]initWithData:entity];
            DDVerifyThread* sendThread = [DDVerifyThread sharedVerifyThread];
            int uid = [downloadFile getUid];
            DDFileInfo* uploadFileInfo = [DDConstants getLocalFileInfoById:uid];
            
//            DDFileInfo* fileInfo = [DDConstants getLocalFileInfoById:fileId];
            //判断需要上传的文件是否是图片，如果是图片，需要首先进行copy，然后再发送上传信息
                if ([[DDConstants getFileInfoType:[uploadFileInfo fileName]]isEqualToString:CLOUD_PHOTO]) {
                    ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
                    [library assetForURL:[uploadFileInfo url] resultBlock:^(ALAsset *asset) {
                        //首先完成拷贝操作，然后再完成发送消息的操作
                        NSString * type = [DDConstants getFileInfoType:[uploadFileInfo fileName]];
                        NSString* filePath = [NSString stringWithFormat:@"%@%@/%@",[AppUtil getDocPath],type,[uploadFileInfo fileName]];
                        [FileOperation writeImage:asset toFileAtPath:filePath];
                        DDUploadFile* uploadFile = [[DDUploadFile alloc]initWithFileInfo:uploadFileInfo];
//                        [[DDVerifyThread sharedVerifyThread]sendMessage:uploadFile];
                        [sendThread uploadFile:downloadFile];
                    } failureBlock:^(NSError *error) {
            
                    }];
                }
                else{
                    [sendThread uploadFile:downloadFile];
                }
            
            
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else if(curCmd == CloudCmd_UploadFile){
            NSLog(@"RECV---收到CloudCmd_UploadFile指令");
            DDUploadFile *uploadFile = [[DDUploadFile alloc]initWithData:entity];
            DDFileInfo* downloadFileInfo = [uploadFile getFileInfo];
            DDVerifyThread* sendThread = [DDVerifyThread sharedVerifyThread];
            int downloadId = [downloadFileInfo fileId];
            long offset = 0;
            long len = 0xFFFFFFFF;
            DDDownloadFile* downloadFile = [[DDDownloadFile alloc]initWithUid:downloadId andOffset:offset andLength:len];
            [sendThread sendMessage:downloadFile];
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else if(curCmd == CloudCmd_UploadAddressBook){
            NSLog(@"RECV---收到CloudCmd_UploadAddressBook指令");
            //发送上传book响应指令
            DDUploadAddressBookACK* uploadAddressBookAck = [[DDUploadAddressBookACK alloc]init];
            DDVerifyThread* sendThread = [DDVerifyThread sharedVerifyThread];
            [sendThread sendMessage:uploadAddressBookAck];
            
            //发送下载book指令
            DDDownLoadAddress* downloadAddress = [[DDDownLoadAddress alloc]initWithOffset:0 andLength:0xFFFFFFFF];
            [sendThread sendMessage:downloadAddress];
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else if(curCmd == CloudCmd_DownloadAddressBook){
            NSLog(@"RECV---收到CloudCmd_DownloadAddressBook");
            //收到该指令之后开始将本地的vcf文件上传至服务器
            DDDownLoadAddress* downloadAddress = [[DDDownLoadAddress alloc]initWithData:entity];
            DDVerifyThread* sendThread = [DDVerifyThread sharedVerifyThread];
            [sendThread uploadAddressBook:downloadAddress];
            
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else if(curCmd == CloudCmd_DownloadAddressBookAck){
            NSLog(@"RECV---收到CloudCmd_DownloadAddressBookAck");
            //收到该指令之后开始接收服务器端的vcf文件
            IOOperation* ioOp = [[IOOperation alloc]init];
            DDDownLoadAddressACK* downAddressACK = [[DDDownLoadAddressACK alloc]initWithData:entity];
            NSLog(@"data length------%d",[[downAddressACK getData]length]);
            DDAddressBookUtils* bookUtils = [[DDAddressBookUtils alloc]init];
            NSLog(@"file length------%d",[downAddressACK getFileLength]);
            NSString* bookPath = [bookUtils getRemoteVcfPath];
            if ([downAddressACK getOffset] == 0 && [downAddressACK getFileLength] != 0) {
                if (bookPath == nil) {
                    [bookUtils createVcfFileWithCode:SERVER_CODE];
                }
                else{
                    NSFileManager* fileManager = [NSFileManager defaultManager];
                    [fileManager removeItemAtPath:bookPath error:nil];
                    [bookUtils createVcfFileWithCode:SERVER_CODE];
                }
            }
            
            NSData* data = [downAddressACK getData];
            NSRange range;
            range.location = 0 ;
            range.length = [downAddressACK getFileLength];
            data = [data subdataWithRange:range];
            long writeOffset = [downAddressACK getOffset];
            //type是0的情况就是正常的数据包
            if([downAddressACK getType]== 0){
                [ioOp writeData:data andOffset:writeOffset andPath:bookPath];
            }
            //剩下的情况说明已经下载到了文件的末尾,并将文件信息存入本地文件文件数组当中
            else{
                //[ioOp writeData:data andOffset:writeOffset andPath:bookPath];
                if ([DDTCPListenThread sharedTCPListener].downloadBookCallback != nil) {
                    //                    [downloadBookCallback onComplete:0];
                    [[DDTCPListenThread sharedTCPListener].downloadBookCallback onComplete:0];
                    downloadBookCallback = nil;
                }
                //                if(.downloadBookCallback != nil){
                //                    [downloadBookCallback onComplete:0];
                //                    downloadBookCallback = nil;
                //                }
                else{
                    TestAddressBook* test = [[TestAddressBook alloc]init];
                    DDAddressBookUtils* bookUtils = [[DDAddressBookUtils alloc]init];
                    [bookUtils createVcfFileWithCode:LOCAL_CODE];
                    NSMutableArray* contactInfos = [test loadVCF:bookPath];
                    
                    if([DDTCPListenThread sharedTCPListener].refreshCallback != nil){
                        //                        [self.refreshCallback onRefreshComplete:0];
                        [[DDTCPListenThread sharedTCPListener].refreshCallback onRefreshComplete:0];
                        [DDConstants setServerContactCount:[contactInfos count]];
                        //FIX ME需要把refresh设置为nil
                        //                        [DDTCPListenThread sharedTCPListener].refreshCallback = nil;
                    }
                    else{
                        for (DDContactInfo* info in contactInfos) {
                            BOOL flag = [test isContactInfoExist:info];
                            if(!flag){
                                ABAddressBookRef addressBook = ABAddressBookCreate();
                                [bookUtils createNewPersonWithAddressBook:addressBook andPerson:info];
                                //                                int count = [DDConstants getServerContactCount] + 1;
                                //                                [DDConstants setServerContactCount:count];
                                
                            }
                        }
                    }
                }
            }
            [bookUtils release];
            [downAddressACK release];
            [ioOp release];
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        else if(curCmd == CloudCmd_DeleteFile){
            NSLog(@"RECV---收到CloudCmd_DeleteFile");
            DDDeleteFile* deleteFile = [[DDDeleteFile alloc]initWithData:entity];
            int deleteId = [deleteFile getDeleteId];
            [deleteFile release];
            int result = 1;
            DDFileInfo* deleteFileInfo = [DDConstants getLocalFileInfoById:deleteId];
            if (deleteFile != nil) {
                result = 0;
                [deleteFileInfo release];
                FileOperation* fo = [[FileOperation alloc]init];
                [fo deleteFileById:deleteId];
                [fo release];
                
                [DDConstants removeFileFromLocalById:deleteId];
                
                DDDeleteFileACK* deleteFileAck = [[DDDeleteFileACK alloc]initWithResult:result];
                [[DDVerifyThread sharedVerifyThread]sendMessage:deleteFileAck];
            }
            
            [sock readDataToLength:HEADER_LENGTH withTimeout:-1 tag:RECV_HEAD_TAG];
        }
        [curHdr release];
        [entity release];
    }
    
    
}


//收到对方的下载命令，发送相应指令，同时发送下载指令
-(void)recvUploadFileCmd:(DDUploadFile*)uploadFile{
    DDUploadFileACK* uploadAck = [[DDUploadFileACK alloc]init];
    [_sendThread sendMessage:uploadAck];
}
+(void)closeAndClear{
    [[_sharedTCPListener recvSocket]disconnect];
    
    _sharedTCPListener = nil;
}

- (void)save:(NSString*)urlString{
    NSLog(@"image path----->%@",urlString);
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    UIImage* image = [UIImage imageWithContentsOfFile:urlString];
    [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {
        if (error) {
            NSLog(@"Save image fail：%@",error);
        }else{
            NSLog(@"Save image succeed.%@",assetURL);
            ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc]init];
            [assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
                //保存成功之后，将文件名，id，文件长度和uri存储在FileInfo当中
                DDFileInfo* fileInfo = [[DDFileInfo alloc]init];
                long fileLength = [[asset defaultRepresentation]size];
                NSString* fileName = [[asset defaultRepresentation]filename];
                [fileInfo setFileLength:fileLength];
                [fileInfo setUrl:assetURL];
                int curId = [DDConstants getGloalId] + 1;
                [DDConstants setGloalId:curId];
                [fileInfo setFileName:fileName];
                fileInfo.fileId = curId;
                fileInfo.url = assetURL;
                [DDConstants addFile:fileInfo andCode:LOCAL_CODE];
                
            } failureBlock:^(NSError *error) {
            }];
        }
    }];
    //    UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
}

- (void)saveV:(NSString*)urlString{
    NSLog(@"org---->%@",urlString);
    // urlString = @"/Users/mars/Library/Application Support/iPhone Simulator/7.0/Applications/5100B004-D9DB-46D5-877F-0CACA7F72699/Documents/video/aaa.mp4";
    //urlString = @"/Users/mars/Library/Application Support/iPhone Simulator/7.0/Applications/5100B004-D9DB-46D5-877F-0CACA7F72699/tmp/aaa.mp4";
    NSLog(@"v path---------------%@",urlString);
    //    [self copyTempVideoToMediaLibrary:urlString];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    if ( UIVideoAtPathIsCompatibleWithSavedPhotosAlbum( urlString )) {
        NSLog(@"-------------save ok");
        //UISaveVideoAtPathToSavedPhotosAlbum(urlString,nil,nil,nil);
    }
    
    [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:urlString]
                                completionBlock:^(NSURL *assetURL, NSError *error) {
                                    if (error) {
                                        NSLog(@"Save video fail:%@",error);
                                    } else {
                                        NSLog(@"Save video succeed.%@",assetURL);
                                    }
                                }];
}

- (void)copyTempVideoToMediaLibrary :(NSString *)videoURL {
    
    dispatch_queue_t mainQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(mainQueue, ^{
        
        ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
        
        ALAssetsLibraryWriteVideoCompletionBlock completionBlock = ^(NSURL *assetURL, NSError *error) {
            NSLog(@"Saved URL: %@", assetURL);
            NSLog(@"Error: %@", error);
            
            if (assetURL != nil) {
                
                AVURLAsset *theAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:videoURL] options:nil];
                
                NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:theAsset];
                
                AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:theAsset presetName:AVAssetExportPresetLowQuality];
                
                [exportSession setOutputURL:[NSURL URLWithString:videoURL]];
                [exportSession setOutputFileType:AVFileTypeQuickTimeMovie];
                
                [exportSession exportAsynchronouslyWithCompletionHandler:^ {
                    switch ([exportSession status]) {
                        case AVAssetExportSessionStatusFailed:
                            NSLog(@"Export session faied with error: %@", [exportSession error]);
                            break;
                        default:
                            //[self mediaIsReady];
                            break;
                    }
                }];
            }
        };
        
        [library writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:videoURL] completionBlock:completionBlock];
    });
}

@end
